#pragma once
/*
日志器模块：
    1. 抽象日志基类
    2. 派生出不同的子类（同布日志器类 & 异步日志器类）

*/
#include "util.hpp"
#include "level.hpp"
#include "message.hpp"
#include "formatter.hpp"
#include "sink.hpp"
#include "looper.hpp"
#include <vector>
#include <list>
#include <atomic>
#include <unordered_map>
#include <cstdarg>
#include <type_traits>

namespace hsl_log
{
    class SyncLogger;
    class AsyncLogger;
    class Logger
    {
    public:
        enum class Type
        {
            LOGGER_SYNC = 0,
            LOGGER_ASYNC
        };
        using ptr = std::shared_ptr<Logger>;
        Logger(const std::string &name,
               Formatter::ptr formatter,
               std::vector<LogSink::ptr> &sinks,
               LogLevel::value level = LogLevel::value::DEBUG) : _name(name), _level(level), _formatter(formatter),
                                                                 _sinks(sinks.begin(), sinks.end())
        {}

        const std::string loggerName() { return _name; }
        LogLevel::value loggerLevel() { return _level; }
        void debug(const char *file, size_t line, const char *fmt, ...)
        {
            // 1.判断是否达到了日志等级
            if (shouldLog(LogLevel::value::DEBUG) == false)
            {
                return;
            }
            // 处理不定参...
            va_list al;
            va_start(al, fmt);
            log(LogLevel::value::DEBUG, file, line, fmt, al);
            va_end(al);
        }
        void info(const char *file, size_t line, const char *fmt, ...)
        {
            if (shouldLog(LogLevel::value::INFO) == false)
                return;
            va_list al;
            va_start(al, fmt);
            log(LogLevel::value::INFO, file, line, fmt, al);
            va_end(al);
        }
        void warn(const char *file, size_t line, const char *fmt, ...)
        {
            if (shouldLog(LogLevel::value::WARN) == false)
                return;
            va_list al;
            va_start(al, fmt);
            log(LogLevel::value::WARN, file, line, fmt, al);
            va_end(al);
        }
        void error(const char *file, size_t line, const char *fmt, ...)
        {
            if (shouldLog(LogLevel::value::ERROR) == false)
                return;
            va_list al;
            va_start(al, fmt);
            log(LogLevel::value::ERROR, file, line, fmt, al);
            va_end(al);
        }
        void fatal(const char *file, size_t line, const char *fmt, ...)
        {
            if (shouldLog(LogLevel::value::FATAL) == false)
                return;
            va_list al;
            va_start(al, fmt);
            log(LogLevel::value::FATAL, file, line, fmt, al);
            va_end(al);
        }

    public:
        // 建造者模式:就是为了解决一个对象构造过于复杂，参数过多的问题，为用户使用提供便利                      降低用户使用的复杂度
        // 1.抽象一个日志建造者类
        //   1.1 设置日志器类型
        //   1.2 将不同类型日志器的创建放到同一个日志建造者类中完成

        class Builder
        {
        public:
            using ptr = std::shared_ptr<Builder>;
            Builder() : _level(LogLevel::value::DEBUG),
                        _logger_type(Logger::Type::LOGGER_SYNC),
                        _looper_type(AsyncType::ASYNC_SAFE) {}
            void buildLoggerName(const std::string &name) { _logger_name = name; }
            void buildLoggerLevel(LogLevel::value level) { _level = level; }
            void buildEnableUnSafeAsync() {_looper_type = AsyncType::ASYNC_UNSAFE; }
            void buildLoggerType(Logger::Type type) { _logger_type = type; }
            void buildFormatter(const std::string pattern) { _formatter = std::make_shared<Formatter>(pattern); }
            void buildFormatter(const Formatter::ptr &formatter) { _formatter = formatter; }
            //添加日志落地目标
            template <typename SinkType, typename... Args>
            void buildSink(Args &&...args)
            {
                auto sink = SinkFactory::create<SinkType>(std::forward<Args>(args)...);
                _sinks.push_back(sink);
            }
            // 纯虚函数，由具体建造者实现
            virtual Logger::ptr build() = 0;

        protected:
            AsyncType _looper_type;
            Logger::Type _logger_type;
            std::string _logger_name;
            LogLevel::value _level;
            Formatter::ptr _formatter;
            std::vector<LogSink::ptr> _sinks;
        };

    protected:
        bool shouldLog(LogLevel::value level) { return level >= _level; }

        // log序列化
        void log(LogLevel::value level, const char *file, size_t line, const char *fmt, va_list al)
        {
            // 2.对fmt格式化字符串和不定参进行字符串组织，得到日志消息的字符串
            char *buf;
            std::string msg;
            int len = vasprintf(&buf, fmt, al);
            if (len < 0)
            {
                msg = "格式化日志消息失败！！";
            }
            else
            {
                msg.assign(buf, len);
                free(buf);
            }
            // 3. 构造LogMsg对象
            //  LogMsg(name, file, line, payload, level)
            LogMsg lm(_name, file, line, std::move(msg), level);
            // 4.通过格式化工具对LogMsg进行格式化，得到格式化后的日志字符串
            std::stringstream ss;
            _formatter->format(ss, lm);
            logIt(std::move(ss.str()));
        }
        virtual void logIt(const std::string &msg) = 0;

    protected:
        std::mutex _mutex;
        std::string _name;
        Formatter::ptr _formatter;           // 格式化
        std::atomic<LogLevel::value> _level; // 限制等级
        std::vector<LogSink::ptr> _sinks;    // 落地方向
    };
    // 同步日志
    class SyncLogger : public Logger
    {
    public:
        using ptr = std::shared_ptr<SyncLogger>;
        SyncLogger(const std::string &name,
                   Formatter::ptr formatter,
                   std::vector<LogSink::ptr> &sinks,
                   LogLevel::value level = LogLevel::value::DEBUG) : Logger(name, formatter, sinks, level)
        {
            std::cout << LogLevel::toString(level) << " 同步日志器: " << name << "创建成功...\n";
        }

    private:
        void logIt(const std::string &msg) override
        {
            std::unique_lock<std::mutex> lock(_mutex);
            if (_sinks.empty())
            {
                return;
            }
            for (auto &it : _sinks)
            {
                it->log(msg.c_str(), msg.size());
            }
        }
    };


    // 异步日志器
class AsyncLogger : public Logger
    {
    public:
        using ptr = std::shared_ptr<AsyncLogger>;
        AsyncLogger(const std::string &name,
                    Formatter::ptr formatter,
                    std::vector<LogSink::ptr> &sinks,
                    LogLevel::value level = LogLevel::value::DEBUG,
                    AsyncType looper_type= AsyncType::ASYNC_SAFE) 
                    :Logger(name, formatter, sinks, level),
                    _looper(std::make_shared<AsyncLooper>(std::bind(&AsyncLogger::backendLogIt, this, std::placeholders::_1),looper_type))
        {
            std::cout << LogLevel::toString(level) << "异步日志器: " << name << "创建成功...\n";
        }

    protected:
        void logIt(const std::string &msg) override
        {
            _looper->push(msg);
        }
        //实际落地函数，将缓冲区中的数据落地
        void backendLogIt(Buffer &msg)
        {
            if (_sinks.empty())
            {
                return;
            }
            for (auto &it : _sinks)
            {
                it->log(msg.begin(), msg.readAbleSize());
            }
        }

    protected:
        AsyncLooper::ptr _looper;
    };


    //本地日志记录器构建器（局部）
    class LocalLoggerBuilder : public Logger::Builder
    {
    public:
        Logger::ptr build() override
        {
            if (_logger_name.empty())
            {
                std::cout << "日志器名称不能为空！！";
                abort();
            }
            if (_formatter.get() == nullptr)
            {
                std::cout << "当前日志器：" << _logger_name << " 未检测到日志格式，默认设置为[ %d{%H:%M:%S}%T%t%T[%p]%T[%c]%T%f:%l%T%m%n ]!\n";
                _formatter = std::make_shared<Formatter>();
            }
            if (_sinks.empty())
            {
                std::cout << "当前日志器：" << _logger_name << " 未检测到落地方向，默认设置为标准输出!\n";
                _sinks.push_back(std::make_shared<StdoutSink>());
            }
            Logger::ptr lp;
            if (_logger_type == Logger::Type::LOGGER_ASYNC)
            {
                lp = std::make_shared<AsyncLogger>(_logger_name, _formatter, _sinks, _level,_looper_type);
            }
            else
            {
                lp = std::make_shared<SyncLogger>(_logger_name, _formatter, _sinks, _level);
            }
            return lp;
        }
    };

    //日志管理器:单例模式（懒汉）
    class loggerManager
    {
    private:
        std::mutex _mutex;
        Logger::ptr _root_logger;
        std::unordered_map<std::string, Logger::ptr> _loggers;//查找效率高

    private:
        //构造函数私有
        loggerManager()
        {
            std::unique_ptr<LocalLoggerBuilder> slb(new LocalLoggerBuilder());
            slb->buildLoggerName("root");
            slb->buildLoggerType(Logger::Type::LOGGER_SYNC);
            _root_logger = slb->build();
            _loggers.insert(std::make_pair("root", _root_logger));
        }
        loggerManager(const loggerManager &) = delete;
        loggerManager &operator=(const loggerManager &) = delete;

    public:
        // 获取单例实例的静态方法
        static loggerManager &getInstance()
        {
            static loggerManager lm;
            return lm;
        }
        // 检查是否存在指定名称的日志记录器
        bool hasLogger(const std::string &name)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            auto it = _loggers.find(name);
            if (it == _loggers.end())
            {
                return false;
            }
            return true;
        }
        // 添加新的日志记录器
        void addLogger(const std::string &name, const Logger::ptr logger)
        {
            if(hasLogger(logger->loggerName())) return;
            std::unique_lock<std::mutex> lock(_mutex);
            _loggers.insert(std::make_pair(name, logger));
        }
        // 获取指定名称的日志记录器
        Logger::ptr getLogger(const std::string &name)
        {
            std::unique_lock<std::mutex> lock(_mutex);
            auto it = _loggers.find(name);
            if (it == _loggers.end())
            {
                return Logger::ptr();//没找到返回空指针
            }
            return it->second;
        }
        // 获取默认日志记录器
        Logger::ptr rootLogger()
        {
            std::unique_lock<std::mutex> lock(_mutex);
            return _root_logger;
        }
    };
    //全局日志建造者
    class GlobalLoggerBuilder : public Logger::Builder
    {
    public:
        Logger::ptr build() override
        {
            if (_logger_name.empty())
            {
                std::cout << "日志器名称不能为空！！";
                abort();
            }
            assert(loggerManager::getInstance().hasLogger(_logger_name) == false);
            if (_formatter.get() == nullptr)
            {
                std::cout << "当前日志器：" << _logger_name << " 未检测到日志格式，默认设置为[ %d{%H:%M:%S}%T%t%T[%p]%T[%c]%T%f:%l%T%m%n ]!\n";
                _formatter = std::make_shared<Formatter>();
            }
            if (_sinks.empty())
            {
                std::cout << "当前日志器：" << _logger_name << " 未检测到落地方向，默认设置为标准输出!\n";
                _sinks.push_back(std::make_shared<StdoutSink>());
            }
            Logger::ptr lp;
            if (_logger_type == Logger::Type::LOGGER_ASYNC)
            {
                lp = std::make_shared<AsyncLogger>(_logger_name, _formatter, _sinks, _level);
            }
            else
            {
                lp = std::make_shared<SyncLogger>(_logger_name, _formatter, _sinks, _level);
            }
            loggerManager::getInstance().addLogger(_logger_name, lp);
            return lp;
        }
    };

}